package org.catpay.modules.app.service.impl;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.ibatis.session.RowBounds;
import org.catpay.common.exception.RRException;
import org.catpay.common.utils.PageUtils;
import org.catpay.common.utils.Query;
import org.catpay.modules.app.contants.SysConfig;
import org.catpay.modules.app.dao.OrderDao;
import org.catpay.modules.app.em.OrderStatusEnum;
import org.catpay.modules.app.em.UserRoleEnum;
import org.catpay.modules.app.entity.OrderDataEntity;
import org.catpay.modules.app.entity.OrderDataEntityDTO;
import org.catpay.modules.app.entity.ProductEntity;
import org.catpay.modules.app.entity.UserEntity;
import org.catpay.modules.app.service.PayService;
import org.catpay.modules.app.service.RewardService;
import org.catpay.modules.app.service.UserService;
import org.catpay.modules.sys.service.BusinessProductService;
import org.catpay.modules.sys.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;

@Service("payService")
public class PayServiceImpl extends ServiceImpl<OrderDao, OrderDataEntity> implements PayService {
	@Autowired
	RewardService rService;
	@Autowired
	AlipayServiceImpl alipayService;
	@Autowired
	private UserService userService;
	@Autowired
	SysConfigService sysConfigService;
	@Autowired
	BusinessProductService pService;
	@Autowired
	OrderDao orderDao;

	@Override
	public String setOrderData(UserEntity user, Long goodsId, int tc, Long addId) {
		OrderDataEntity order = new OrderDataEntity();
		ProductEntity goods = pService.selectById(goodsId);
		if (goods == null) {
			throw new RRException("产品不存在：" + goodsId);
		}
		String orderNo = "O_" + IdUtil.fastSimpleUUID();
		order.setAmount(goods.getPrice().multiply(new BigDecimal(tc)));
		if (goods.getId() == 2 || goods.getId() == 3) {
			if (user.getLevel() != 0) {
				ProductEntity goods1 = pService.selectById(user.getLevel());
				if (goods1 != null) {
					order.setAmount((goods.getPrice().subtract(goods1.getPrice())).multiply(new BigDecimal(tc)));
				}
			}
		}
		order.setImage(goods.getImgUrl());
		order.setGoodsId(goodsId);
		order.setGoodsName(goods.getTitle());
		order.setGoodsPrice(goods.getPrice());
		order.setGoodsType(goods.getType());
		order.setNickName(user.getNickName());
		order.setOrderNo(orderNo);
		order.setPhone(user.getPhone());
		order.setStatus(OrderStatusEnum.待付款.getValue());
		order.setTotalCount(tc);
		order.setUserId(user.getId());
		order.setAddressId(addId);
		baseMapper.insert(order);
		return orderNo;
	}

	@Override
	public String createAlipayOrder(String outTradeNo) {
		OrderDataEntity entity = new OrderDataEntity();
		entity.setOrderNo(outTradeNo);
		entity = baseMapper.selectOne(entity);
		if (entity == null) {
			throw new RRException("订单不存在：" + outTradeNo);
		}
		String body = "云猫商品";
		String subject = entity.getGoodsName();
		String totalAmount = entity.getAmount().toString();
		String notifyUrl = sysConfigService.getValue(SysConfig.ALINOTIFYURL);
		return alipayService.createAlipayOrder(body, subject, outTradeNo, totalAmount, notifyUrl);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public boolean verifyNotify(Map para) {
		return alipayService.verifyNotify(para);
	}

	@Override
	public void payNotice(String outTradeNo) {
		OrderDataEntity entity = new OrderDataEntity();
		entity.setOrderNo(outTradeNo);
		entity = baseMapper.selectOne(entity);
		if (entity != null) {
			if (entity.getStatus() == OrderStatusEnum.待付款.getValue()) {
				if (entity.getGoodsType() == 0) {
					if (entity.getGoodsId() == 1 || entity.getGoodsId() == 2 || entity.getGoodsId() == 3) {
						UserEntity user = userService.selectById(entity.getUserId());
						user.setRole(UserRoleEnum.供应商.getValue());
						user.setLevel(entity.getGoodsId().intValue());
						userService.updateById(user);
					}
					entity.setStatus(OrderStatusEnum.已完成.getValue());
				} else {
					entity.setStatus(OrderStatusEnum.待发货.getValue());
				}
				baseMapper.updateById(entity);

				// 给奖励
				rService.doReward(entity);
			}
		}
	}

	@Override
	public List<OrderDataEntity> getOrder(Long userId, String status, String pageNo, String pageSzie) {
		List<OrderDataEntity> orderList = baseMapper.selectPage(
				new RowBounds(Integer.parseInt(pageNo), Integer.parseInt(pageSzie)),
				new EntityWrapper<OrderDataEntity>().eq("user_id", userId).eq(!"0".equals(status), "status", status));

		return orderList;
	}

	@Override
	public void cancelOrder(Long userId, String outTradeNo) {
		OrderDataEntity entity = new OrderDataEntity();
		entity.setOrderNo(outTradeNo);
		entity.setUserId(userId);
		entity = baseMapper.selectOne(entity);
		if (entity == null) {
			throw new RRException("订单不存在：" + outTradeNo);
		}
		if (entity.getStatus() != OrderStatusEnum.待付款.getValue()) {
			throw new RRException("该订单状态下无法取消：" + outTradeNo);
		}
		entity.setStatus(OrderStatusEnum.已取消.getValue());
		baseMapper.updateById(entity);
	}

	@Override
	public PageUtils getAllOrder(Map<String, Object> params) {
		String orderId = MapUtils.getString(params, "orderId");
		Integer status = MapUtils.getInteger(params, "status");
		Long userId = MapUtils.getLong(params, "userId");
		Page<OrderDataEntity> page = this.selectPage(new Query<OrderDataEntity>(params).getPage(),
				new EntityWrapper<OrderDataEntity>().eq(StrUtil.isNotBlank(orderId), "order_no", orderId)
						.eq(userId != null, "user_id", userId).eq(status != null && status != 99, "status", status)
						.orderDesc(Arrays.asList("create_time")));
		return new PageUtils(page);
	}

	@Override
	public void changeOrderStatus(String orderId, int status) {
		OrderDataEntity o = this.getOneOrder(orderId);
		if (o == null)
			throw new RRException("订单不存在");

		if (o.getStatus() == OrderStatusEnum.已完成.getValue() || o.getStatus() == OrderStatusEnum.已失效.getValue()
				|| o.getStatus() == OrderStatusEnum.已取消.getValue() || o.getStatus() == OrderStatusEnum.已退款.getValue())
			throw new RRException("该订单状态不能修改");

		OrderDataEntity order = new OrderDataEntity();
		order.setStatus(status);
		this.update(order, new EntityWrapper<OrderDataEntity>().eq("order_no", orderId));
	}

	@Override
	public OrderDataEntity getOneOrder(String orderId) {
		List<OrderDataEntityDTO> list = orderDao.getOneOrder(orderId);
		if (CollectionUtil.isEmpty(list))
			return new OrderDataEntityDTO();
		return list.get(0);
	}

	@Override
	public boolean updateOrder(OrderDataEntity params) {
		OrderDataEntity o = this.getOneOrder(params.getOrderNo());

		if (o.getStatus() == OrderStatusEnum.已完成.getValue() || o.getStatus() == OrderStatusEnum.已失效.getValue()
				|| o.getStatus() == OrderStatusEnum.已取消.getValue() || o.getStatus() == OrderStatusEnum.已退款.getValue())
			throw new RRException("该状态下的订单不能修改");
		if (o.getStatus() != OrderStatusEnum.待付款.getValue() && o.getStatus() != OrderStatusEnum.申请退款.getValue()) {
			if (o.getAmount().equals(params.getAmount()))
				throw new RRException("该订单状态不能修改金额");
		}
		if (o.getStatus() != OrderStatusEnum.待付款.getValue() && o.getStatus() != OrderStatusEnum.待发货.getValue()) {
			if (o.getTotalCount() != params.getTotalCount())
				throw new RRException("该订单状态不能修改数量");
		}

		return this.update(params, new EntityWrapper<OrderDataEntity>().eq("order_no", params.getOrderNo()));
	}

	@Override
	public OrderDataEntity getOrderData(Long userId) {

		return baseMapper.selectById(userId);
	}

}
